package pers.wwz.study.springbootparams.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/param")
public class HeaderController {

    /**
     * 绑定请求参数{不区分大小写,但是格式不能变(中间横线不能省略)}
     * @param host
     * @param userAgent
     * @param cacheControl
     * @param response
     * @return 结果
     */
    @GetMapping("/header")
    @ResponseBody
    public String getHeader(@RequestHeader(value = "Host") String host,
                            @RequestHeader(value = "User-Agent") String userAgent,
                            @RequestHeader(value = "Cache-Control", required = false) String cacheControl,
                            HttpServletResponse response) {

        log.info("host:{}", host);
        log.info("User-Agent:{}", userAgent);
        log.info("Cache-Control:{}", cacheControl);

        // 设置响应头
        response.setHeader("Cache-Control", "no-cache,no-store,must-revalidate");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);

        return "OK";
    }


    /**
     * 可以将所有请求头信息全部打印出来。
     * @param headers
     * @return
     */
    @GetMapping("/allHeaders")
    public ResponseEntity<Map<String, List<String>>> allHeaders(@RequestHeader HttpHeaders headers) {
        Map<String, List<String>> valueMap = new HashMap<>();
        for (String header : headers.keySet()) {
            valueMap.put(header, headers.get(header));
            log.info("header[{}]={}", header, headers.get(header));
        }
        // 通过ResponseEntity设置响应头
        ResponseEntity<Map<String, List<String>>> entity = ResponseEntity.status(HttpStatus.OK)
                .header("new header", UUID.randomUUID().toString()).body(valueMap);
        return entity;
    }

}
